/**
 * 类似华为手机的下拉刷新
 */
import React, { Component } from 'react';
import {
  Text,
  Animated,
  Easing
} from 'react-native';
import { SmartRefreshControl, AnyHeader } from 'react-native-smartrefreshlayout';
import Icon from 'react-native-vector-icons/Ionicons';
import { SkypeIndicator } from 'react-native-indicators';
import adapt from '../utils/adapt';

const AnimatedIcon = Animated.createAnimatedComponent(Icon);

export default class AndroidRefreshControlComponent extends Component {
  state = {
    text: '下拉推荐',
    rotate: new Animated.Value(0),
    refreshing: false
  }
  _onPullDownToRefresh = () => {
    this.setState({ text: '下拉推荐', refreshing: false });
    Animated.timing(this.state.rotate, { toValue: 0, duration: 197, useNativeDriver: true, easing: Easing.linear() }).start();
  }
  _onReleased = () => {
    this.setState({ refreshing: true, text: '推荐中' });
  }
  _onReleaseToRefresh = () => {
    this.setState({ text: '松开推荐' });
    Animated.timing(this.state.rotate, { toValue: 1, duration: 197, useNativeDriver: true, easing: Easing.linear() }).start();
  }
  _onRefresh = () => {
    this.props.onRefresh && this.props.onRefresh();
  }
  finishRefresh = (params) => {
    this._refreshc && this._refreshc.finishRefresh(params);
  }
  shouldComponentUpdate(nextState, nextProps) {
    return nextState.text !== this.state.text || nextState.rotate !== this.state.rotate ||
      nextProps.onRefresh !== this.props.onRefresh || nextState.refreshing !== this.state.refreshing;
  }
  render() {
    return (
      <SmartRefreshControl primaryColor='#ededed'
        style={{ flex: 1 }}
        ref={ref => this._refreshc = ref}
        children={this.props.children}
        onRefresh={this._onRefresh}
        onPullDownToRefresh={this._onPullDownToRefresh}
        onHeaderReleased={this._onReleased}
        onReleaseToRefresh={this._onReleaseToRefresh}
        headerHeight={adapt(100)}
        HeaderComponent={
          <AnyHeader style={{
            height: adapt(100),
            flexDirection: 'row',
            alignItems: 'center',
            justifyContent: 'center',
          }}>
            {this.state.refreshing ? <SkypeIndicator style={{ flex: 0 }} size={adapt(24)} color={themeColor} /> :
              <AnimatedIcon style={{
                transform: [{
                  rotate: this.state.rotate.interpolate({
                    inputRange: [0, 1],
                    outputRange: ['180deg', '0deg']
                  })
                }]
              }} name="md-arrow-up" color={themeColor} size={adapt(24)} />}
            <Text style={{ marginLeft: adapt(15), color: themeColor }}>{this.state.text}</Text>
          </AnyHeader>
        }
      />
    )
  }
}